import React, { useEffect, useState } from 'react'
import { useNavigate, useLocation, Routes, Route } from 'react-router-dom'
import { Layout, Menu, Dropdown, Button, Modal, message } from 'antd'
import { 
  MonitorOutlined, 
  DownOutlined, 
  UserOutlined,
  LineChartOutlined,
  MessageOutlined,
  TeamOutlined
} from '@ant-design/icons'
import { useUserStore } from '../stores/user'
import Dashboard from './components/Dashboard.tsx'
import Analysis from './components/Analysis.tsx'
import SelfCenter from './components/SelfCenter/SelfCenter.tsx'
import Flip from './components/Flip'
import './Main.less'
import { ava_base_url } from '../utils'
import { Member } from './components/Member/index.tsx'

const { Header, Sider, Content } = Layout

const Main: React.FC = () => {
  const navigate = useNavigate()
  const location = useLocation()
  const { logout, userInfo } = useUserStore()
  const [selectedValue, setSelectedValue] = useState('/dashboard')
  // @ts-ignore
  const userInfoData = userInfo.userInfo || {}
  // @ts-ignore
  const { nickname, avatar } = userInfoData || {}
  

  useEffect(() => {
    const keys = ['/dashboard', '/analysis', '/flip', '/self', '/member']
    if (keys.includes(location.pathname)) {
      setSelectedValue(location.pathname)
    }
  }, [location.pathname])
  // 菜单项配置
  const menuItems = [
    {
      key: '/dashboard',
      icon: <MonitorOutlined />,
      label: '仪表盘',
    },
    {
      key: '/analysis',
      icon: <LineChartOutlined />,
      label: '报表分析',
    },
    {
      key: '/flip',
      icon: <MessageOutlined />,
      label: '翻牌列表',
    },
    {
      key: '/member',
      icon: <TeamOutlined />,
      label: '成员列表',
    },
    {
      key: '/self',
      icon: <UserOutlined  />,
      label: '个人中心',
    },
  ]

  // 处理菜单选择
  const handleMenuSelect = ({ key }: { key: string }) => {
    navigate(key)
    setSelectedValue(key)
  }

  // 处理下拉菜单命令
  const handleCommand = async ({ key }: { key: string }) => {
    if (key === 'logout') {
      Modal.confirm({
        title: '提示',
        content: '确定要退出登录吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: async () => {
          try {
            await logout()
            navigate('/login')
            message.success('已退出登录')
          } catch (error) {
            message.error('退出登录失败')
          }
        },
        onCancel: () => {
          // 用户取消操作
        }
      })
    } else if (key === 'profile') {
      // TODO: 跳转到个人信息页面
      navigate('/self')
      setSelectedValue('/self')
    }
  }

  // 用户下拉菜单项
  const userMenuItems = [
    {
      key: 'profile',
      label: '个人信息',
    },
    {
      key: 'logout',
      label: '退出登录',
    },
  ]

  // 获取页面标题
  const getPageTitle = () => {
    const currentPath = location.pathname
    switch (currentPath) {
      case '/dashboard':
        return '仪表盘'
      case '/analysis':
        return '报表分析'
      case '/member':
        return '成员列表'
      case '/self':
        return '个人中心'
      case '/flip':
        return '翻牌列表'
      default:
        return '仪表盘'
    }
  }

  return (
    <Layout className="main-container">
      {/* 侧边栏 */}
      <Sider width={160} className="aside">
        <div className="logo">
          <img src={`${ava_base_url}${avatar}`} alt="Logo" />
          <span>口袋助手</span>
        </div>
        
        <Menu
          mode="inline"
          defaultSelectedKeys={['/dashboard']}
          items={menuItems}
          className="menu"
          selectedKeys={[selectedValue]}
          onClick={handleMenuSelect}
        />
      </Sider>
      
      {/* 主要内容区域 */}
      <Layout className="content-container">
        {/* 顶部导航栏 */}
        <Header className="header">
          <div className="header-left">
            <h2>{getPageTitle()}</h2>
          </div>
          <div className="header-right">
            <Dropdown
              menu={{
                items: userMenuItems,
                onClick: handleCommand,
              }}
            >
              <Button type="text" className="user-dropdown">
                {nickname}
                <DownOutlined />
              </Button>
            </Dropdown>
          </div>
        </Header>
        
        {/* 内容区域 */}
        <Content className="main">
          <Routes>
            <Route path="/dashboard" element={<Dashboard />} />
            <Route path="/analysis" element={<Analysis />} />
            <Route path="/flip" element={<Flip />} />
            <Route path="/member" element={<Member />} />
            <Route path="/self" element={<SelfCenter />} />
            <Route path="*" element={<Dashboard />} />
          </Routes>
        </Content>
      </Layout>
    </Layout>
  )
}

export default Main 